package com.authorityManagement.service.impl;

import com.authorityManagement.entity.Menu;
import com.authorityManagement.service.RouterService;
import com.authorityManagement.vo.RouterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class RouterServiceImpl implements RouterService {
      
      
      @Override
      public List<RouterVo> queryRouterMenuList(List<Menu> menuList, Long pid) {
            List<RouterVo> routerVoList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(menuList)) {
                  menuList.stream()
                        .filter(item->item!=null&& item.getPid().equals(pid))
                        .forEach(item->{
                              RouterVo routerVo = new RouterVo();
                              routerVo.setName(item.getMenuName());
                              routerVo.setPath(item.getPath());
                              if (item.getPid() == 0) {
                                    routerVo.setComponent("Layout");
                                    routerVo.setAlwayShow(true);
                              }else{
                                    routerVo.setComponent(item.getComponent());
                                    routerVo.setAlwayShow(false);
                              }
                              routerVo.setMeta(routerVo.new Meta(item.getMenuName(), item.getIcon(), Arrays.asList(item.getPerms().split(","))));
                              List<RouterVo> childrenRouterVoList= queryRouterMenuList(menuList, item.getId());
                              routerVo.setChildren(childrenRouterVoList);
                              routerVoList.add(routerVo);
                        });
            }
            return routerVoList;
      }
      
      @Override
      public List<Menu> queryMenuList(List<Menu> menuList, Long pid) {
            List<Menu> menus = new ArrayList<>();
            if (!CollectionUtils.isEmpty(menuList)) {
                  menuList.stream()
                        .filter(item -> item != null && item.getPid().equals(pid))
                        .forEach(item->{
                              Menu menu = new Menu();
                              BeanUtils.copyProperties(item, menu);
                              List<Menu> childrenMenus = queryMenuList(menuList, item.getId());
                              menu.setChildrenMenuList(childrenMenus);
                              menus.add(menu);
                        });
            }
            return menus;
      }
}
